import express from 'express';
import moment from 'moment';
import { Checkin, User } from '../../modal/index'; // 数据库实体类
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import { checkPermission, addMoney, sendMuban } from '../../utils/utils'; // 工具类
import baseDao from '../../lib/baseDao'; // 用于获取实例化的sequelize
import CONFIG from '../../../config/config.config'; // 全局配置

const router = express.Router();
const minLevel = 0; // 允许调用接口的最低等级

router.post('/', async function (Request, Response, next) {
  // Checkin .Modal.sync();
  let param = Request.body
  const transaction = await baseDao.sequelize.transaction() // 事务
  // 权限校验
  let originGold = 0
  await checkPermission(Request, Response, minLevel).then(res => {
    param.userId = res.id
    param.openId = res.openId
    originGold = res.gold
  })
  param.gold = CONFIG.checkInGold

  let addParam = {
    userId: param.userId,
    title: '每日签到送积分',
    addGold: param.gold, // 要加的积分
  }
  await addMoney(addParam, transaction, Response).then(async res => {
    console.log('增加成功，当前积分：', res)
  })

  // 签到
  Checkin.Modal.create(param, { transaction: transaction }).then(async res => {
    if (res && res.id) {
      await transaction.commit() // 提交事务
      if (param.formId) {
        let mubanParam = {
          page: param.page, // 点击模板跳转页面
          formId: param.formId,
          openId: param.openId,
          templateId: CONFIG.checkinId, // 签到模板ID
          data: {
            keyword1: {
              value: `用户积分+${CONFIG.checkInGold}`
            },
            keyword2: {
              value: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
            },
          }
        }
        sendMuban(mubanParam, Response) // 发送模板消息
      }
      Response.json({
        data: param.gold,
        message: "success"
      });
    } else {
      await transaction.rollback() // 回滚
      Response.status(300).send({ message: "添加签到记录失败" });
    }
  }).catch(async err => {
    console.log(err)
    await transaction.rollback() // 回滚
    Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
  });
});

module.exports = router;